<template>
    <div class="bi-file" :class="[image?'field-image':'field-file','image-'+previewType]"  >
        <div class="bi-file-content" ref="fileContent" v-if="show" >
            <div draggable="true" class="item-box" v-for="(item,index) in list" :key="item+'_'+index" :style="itemStyle" :data-drag="item">
                <div class="disabled-label" v-if="disabled"><i class="fa fa-ban"></i></div>
                <div class="image-mask" v-if="image"></div>
                <div class="image-content" v-if="image">
                    <img :src="imageUrl(item)" />
                </div>
                <div class="file-content"  v-if="!image" >
                    <bi-icon :data="getIcon(item)" :loading="loading" ></bi-icon> <div class="title" v-if="!loading">{{getFileTitle(item)}}</div>
                </div>
                <div class="ctrl-box">
                    <label class="input-btn btn" title="删除" @click="del(index)" >
                        <span><i class="fa fa-close"></i></span> 
                    </label>
                    <label class="input-btn btn"  title="信息" @click="showInfo(info[item])" v-if="info[item] && info[item]['title'] && !loading" >
                       <span><i class="fa fa-info-circle"></i></span> 
                    </label>
                </div>
            </div>

           
        </div>
        <div   class="item-box file-upload" :style="itemStyle" v-if = "(multiple && list.length < max )|| list.length == 0">
                <div class="disabled-label" v-if="disabled"><i class="fa fa-ban"></i></div>
                
                <label class="input-btn btn " title="上传">
                        <span><i class="fa fa-upload"></i></span>
                        <input type="file" @change="uploadFile"  :disabled="disabled"   />
                </label>

                <label class="input-btn btn" title="打开" @click="openDialog" v-if="openFileShow" >
                    <span><i class="fa fa-folder-open-o"></i></span> 
                </label>
            </div>
    </div>
</template>

<script>
import FieldMixin from '../fieldMixin.js';
import {getIcon} from '../file.js';
import dragsort from '../dragsort.js';
export default{
    mixins:[FieldMixin],
    emits:['upload'],
    computed:{
        openFileShow(){
            return typeof window.__bi_file_open =="function";
        },
        infoFileShow(){
            return typeof window.__bi_file_info =="function";
        },
        itemStyle(){

            let height,width;

            if (this.image){
                if (this.previewWidth=='' && this.previewHeight==''){
                    switch(this.previewType){
                        case 'square':
                        case 'circle':
                            width = 150;
                            height =  150;
                        break;
                        case 'rectangle':
                            width = 250;
                            height =  150;
                        break;
                    }
                }else{
                    switch(this.previewType){
                        case 'square':
                        case 'circle':
                            width = this.previewWidth;
                            height =  this.previewWidth;
                        break;
                        case 'rectangle':
                            width = this.previewWidth;
                            height =  this.previewHeight;
                        break;
                    }
                }
            }

            return {
                width:width+ 'px',
                height:height+ 'px'
            }
        }
    },
    data(){

        let list = [];
        
        if (this.modelValue){
            list = this.modelValue.split(this.valueSplit);
        }

        return {
            list,
            show:true,
            info:{},
            loading:false,
            extList:[]
        }
    },
    watch:{
        list:{
            handler(val){
                val  = val.join(this.valueSplit);
                this.$emit('update:modelValue',val);
                this.$emit('change',val);
                this.valueChange(val);
            },
            deep:true
        }
    },
    props:{
        multiple:{
            type:Boolean,
            default:false
        },
        max:{
            type:Number,
            default:10
        },
        param:{
            type:Object,
            default:{}
        },
        ext:{
            type:[String,Array],
            default:''
        },
        image:{
            type:Boolean,
            default:false
        },
        valueSplit:{
            type:String,
            default:','
        },
        previewType:{
            type:String,
            default:'rectangle' //square,circle,rectangle
        },
        previewWidth:{
            type:[Number,String],
            default:''
        },
        previewHeight:{
            type:[Number,String],
            default:''
        }
    },
    methods:{
         
        uploadFile(event){

            var files = event.target.files;
            if (files.length ==0){
                this.$alert('请选择要上传的文件');
                return
            }
            
            let file = files[0];
 
            let fileInfo  = {
                ext:file.name.split('.').pop(),
                title:file.name.split('.').slice(0,-1).join('.'),
                size:file.size,
                date:this.time(),
            }

            var ext = file.name.substring(files.name.lastIndexOf('.')+1).toLowerCase();
            
            if (this.extList.length > 0 && this.extList.indexOf(ext) == -1){
                this.$alert('只能上传['+this.extList.join(',')+']格式的文件');
                return
            }


            if (typeof window.__bi_file_upload =="function"){
                
                 window.__bi_file_upload(file,this.param,(filePath)=>{
                    this.addFile(filePath,fileInfo);
                });
            }

            this.$emit('upload',file,this.param,(filePath)=>{
                this.addFile(filePath,fileInfo);
            });
        },
        time(){
            const today = new Date();
            const year = today.getFullYear();
            const month = (today.getMonth() + 1).toString().padStart(2, '0'); // +1 因为月份是从0开始的
            const date = today.getDate().toString().padStart(2, '0');
            const hours = today.getHours().toString().padStart(2, '0');
            const minutes = today.getMinutes().toString().padStart(2, '0');
            const seconds = today.getSeconds().toString().padStart(2, '0');

            const dateTime = `${year}-${month}-${date} ${hours}:${minutes}:${seconds}`;
            return dateTime;
        },
        openDialog(){
            window.__bi_file_open((file)=>{
                this.addFile(file);
            },
            this.extList)
        },
        addFile(file,info){
            
            if (this.multiple){
                this.list.push(file);
            }else{
                this.list = [file];
            }

            if (info!== undefined){
                this.info[file] = info;

                let str =sessionStorage.getItem('bi-file-info');
                let infolist = {};
                if (str){
                    infolist = JSON.parse(str);
                }
                infolist[file] = info;
                sessionStorage.setItem('bi-file-info',JSON.stringify(infolist));
            }else{
                this.flashFileInfo();
            }
        },
        del(index){
            this.list.splice(index,1);
        },
        showInfo(info){
            console.log(info);
        },
        getFileName(file){
            if (file){
                return file.split('/').pop();
            }
        },

        getFileTitle(file){
            if (this.info[file] && this.info[file].title && this.info[file].title!=''){
                return this.info[file].title+'.'+this.info[file].ext;
            }else{
                return file.split('/').pop();
            }
        },
        flashFileInfo(){
            let str =sessionStorage.getItem('bi-file-info');
            let infolist = {};
            if (str){
                infolist = JSON.parse(str);
            }

            let noInfo = [];
            
            for(let i=0;i<this.list.length;i++){
                if (infolist[this.list[i]]){
                    this.info[this.list[i]] = infolist[this.list[i]];
                }else{
                    noInfo.push(this.list[i]);
                }
            }

            if (noInfo.length && typeof window.__bi_file_info == 'function'){
                this.loading = true;
                window.__bi_file_info(noInfo,(data)=>{
                     for(let i=0;i<noInfo.length;i++){
                        let file = noInfo[i];
                        let _data = {empty:true};
                        
                        for(let j=0;j<data.length;j++){
                            if (data[j].file == file){
                                _data = data[j];
                                break;
                            }
                        }
                        
                        infolist[file] = _data;
                        this.info[file] =  _data;
                        
                    }
                    sessionStorage.setItem('bi-file-info',JSON.stringify(infolist));
                    this.loading = false;
                });
               
                
             }
        },
        imageUrl(file){
            if (typeof window.__bi_upload_url == 'function'){
                return window.__bi_upload_url(file);
            }
        }
    },
    mounted(){
        
        if (this.ext == '' && this.image){
            this.extList = ['jpg','png','gif','jpeg','bmp','webp'];
        }else{
            this.extList = Array.isArray(this.ext) ? this.ext : this.ext.split(','); 
        }
        
        this.flashFileInfo();
        let drager  = new dragsort(this.$refs.fileContent,{
            callback:(value)=>{
                this.list = value;
            }
        });
        
    }
}
</script>



<style>
.bi-file {
    display: flex;
    flex-wrap: wrap;
    gap: 10px;
}
.bi-file  .bi-file-content{
    display: flex;
    flex-wrap: wrap;
    gap: 10px;
}
.bi-file   .item-box{
    padding: 3px;
    position: relative;
    border-radius: var(--bs-border-radius);
    background-color: var(--bs-tertiary-bg);
    border: var(--bs-border-width) solid var(--bs-border-color);
    flex-shrink: 0;
}
.bi-file.field-image .item-box{
    width: 150px;
    height:150px;
}

.bi-file.field-image .item-box.drager-move{
    background-color:transparent;
    border: 1px dashed var(--bs-border-color);
}


.bi-file.field-image .item-box.drager-move > *{
    display: none;
}
.bi-file.image-circle .item-box{
    border-radius: 50%;
}

.bi-file.image-rectangle .item-box{
    width: 250px;
}

.bi-file.field-file .item-box{
    width: 300px;
    height:50px;
    display: flex;
    padding: 10px;
    justify-content: space-between;
    align-items: center;
}


.bi-file .item-box .disabled-label{
    width: 100%;
    height: 100%;
    justify-content: center;
    align-items: center;
    display: flex;
    color: #EEE;
    font-size: 50px;
    left: 0;
    top: 0;
    position: absolute;
    z-index: 20;
    background-color: #FFF;
}

.bi-file .item-box .input-btn input{
    display: none;
}

.bi-file .item-box .input-btn .fa{
    margin-right: 0;
}

.bi-file .item-box.file-upload{
    justify-content: center;
    align-items: center;
    display: flex;
    border-style: dashed;
}

.bi-file .item-box .input-btn{
    border-color:rgba(255, 255, 255,0.7);
    background-color: #FFF;
}

.bi-file .item-box .input-btn:hover{
    border-color:var(--bs-border-color);
    background-color:rgba(255, 255, 255,0.9);
}

.bi-file.field-image .image-mask{
    width: 100%;
    height: 100%;
     z-index: 2;
    position: absolute;
    top: 0;
    left: 0;
    font-size: 12px;
}
.bi-file.field-image .image-content{
    display: flex;
    justify-content: center;
    align-items: center;
    width: 100%;
    height: 100%;
    background-color: #eeeeee;
    position: relative;
    z-index: 1;
}



.bi-file.field-image .image-content img{
     max-height: 100%;
     max-width: 100%;      
}

.bi-file.field-image .ctrl-box{
    position: absolute;
    right: 0px;
    bottom: 0px;
    z-index: 10;
    padding: 10px;
    display: flex;
    flex-direction: row;
   
}
.bi-file.field-image .ctrl-box .btn{
    --bs-btn-padding-x:0;
    --bs-btn-padding-y:0;
    width: 30px;
    height: 30px;
    justify-content: center;
    align-items: center;
    display: flex;
 }

 .bi-file.field-file .file-content{
    display: flex;
    align-items: center;
 }

 .bi-file.field-file .file-content .title{
    font-size: 12px;
    overflow: hidden;
    max-width: 160px;
    margin-left: 5px;
 }
</style>